package com.ichinait.bridge.controller;

import com.alibaba.fastjson.JSON;
import com.ichinait.bridge.db.entity.User;
import com.ichinait.bridge.service.UserService;
import com.xiaoleilu.hutool.crypto.digest.DigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping("toLogin")
    public String toLoginPage(){
        LOGGER.debug("跳转登录页");
        return "bridge/index";
    }


    @RequestMapping("login")
    @ResponseBody
    public Object login(User user, HttpServletRequest httpServletRequest){
        LOGGER.debug("登录：{}",JSON.toJSONString(user));
        Map<String, Object> rtnObj = new HashMap<>();
        User login = userService.login(user);
        if(login != null){
            httpServletRequest.getSession().setAttribute("me", login);
            rtnObj.put("code", 1);
        }else{
            rtnObj.put("code", 0);
        }
        return rtnObj;
    }

    @RequestMapping("logout")
    public String toPage(HttpServletRequest httpServletRequest){
        httpServletRequest.getSession().removeAttribute("me");
        return "bridge/index";
    }
}
